package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;

import org.json.JSONArray;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.MyactivitesAdapter;
import biznussoft.fieldservice360.model.MyActivitiesModel;
import biznussoft.fieldservice360.service.MyServiceClass;
import biznussoft.fieldservice360.utils.Session;

import com.google.gson.Gson;

public class MyActivitiesMasterFragment  extends BaseFragment{
	private ListView lv;
	private ArrayList<MyActivitiesModel> list;
	private MyBroadCastReceiver mReceiver;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.inventory, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		String url = Session.sInstanceUrl+"/services/apexrest/RESTAPIDataService";
		getActivity().startService(new Intent(getActivity(),MyServiceClass.class).putExtra("URL", url));
		mReceiver = new MyBroadCastReceiver();
		lv = (ListView) getView().findViewById(R.id.listview);
	}

	@Override
	public void onResume() {
		getActivity().registerReceiver(mReceiver, new IntentFilter("RESPONSE"));
		super.onResume();
	}
	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	class MyBroadCastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {

			try{
				String response =  intent.getStringExtra("Response");
				JSONArray jsonArray = new JSONArray(response);
				list = new ArrayList<MyActivitiesModel>();
				Gson _gson = new Gson();
				for (int i = 0; i < jsonArray.length(); i++) {
					if (!jsonArray.isNull(i)) {
						MyActivitiesModel bean = _gson.fromJson(jsonArray.getString(i),	MyActivitiesModel.class);
						list.add(bean);                   
					}
				}                                                                                        
				showRecords();

			}catch(Exception ex){
				Log.i("RGT","Excption is  :"+ex.getMessage());
			}


		}
	}
	public void showRecords(){
		MyactivitesAdapter adapter = new MyactivitesAdapter(getActivity(),list);
		lv.setAdapter(adapter);
	}

	
}
